package com.hk.handler;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.hk.commons.CommonResult;
import com.hk.model.Admin;
import com.hk.model.vo.Result;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.JedisUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/10 19:12
 * @Statement: 登录认证拦截器
 */
public class MyTologinInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("该预处理拦截器已执行。。。。。。。。。。前");
        CharacterEncoding.setCharacterEncodingResp(request,response,"UTF-8");
        Jedis jedis = JedisUtil.getJedis();
        //        redis获取登录成功信息
        String admin = jedis.get("admin");
        String toJSONString = null;
        if (admin == null) {
            PrintWriter out = response.getWriter();
            Result result = CommonResult.acResult(null);
            Gson gson = new Gson();
            String toJson = gson.toJson(result);
            out.write(toJson);
            out.flush();
            out.close();
            return false;
        }
        return true;
//        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("MyInterceptor执行了。。。。。。后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("页面执行完执行。。。。。最后");

    }
}
